from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.contrib.auth.decorators import login_required


# Create your views here.

@login_required(login_url='/reader/login')
def readerView(request):
    title = "个人中心"
    # 渲染
    return render(request, "reader.html", locals())


def loginView(request):
    """
    登录视图函数
    """
    title = "用户登录"
    # 判断请求方式
    if request.method == "POST":
        username = request.POST.get('username', "")
        password = request.POST.get('password', "")
        # 查询username的数据是否在内置模型User
        if User.objects.filter(username=username):
            # 验证
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return redirect(reverse('reader:reader'))
        else:
            # 注册
            state = "注册成功"
            d = dict(username=username, password=password, is_staff=1, is_active=1)
            user = User.objects.create_user(**d)
            user.save()
        print('000000000000000000000000000000000000000wefwefwedfdwfwefjiefjejiijewjjjj')
    return render(request, 'login.html', locals())

def logoutView(request):
    # 调用Django的内置函数
    logout(request)
    # 网页重定向到首页
    return redirect(reverse('index:index'))
